package java_DesignPattern.CreatorPattern.SingletonPattern.tryDestruction.invoke;

/**
 * 通过反射破坏单例模式
 * 以静态内部类为例(其余方式也可被破坏),仅有枚举可以避免
 */
public class Singleton {

    //保证可见性与极端有序性
    private static volatile boolean flag = false;

    //私有化构造方法
    private Singleton(){

        //反射破坏解决方式,通过synchronized与volatile保证极端情况可见有序性问题
        synchronized (Singleton.class) {
            if (flag) {
                throw new RuntimeException("Cannot create multiple objects repeatedly");
            }
            flag = true;
        }
    }

    private static class SingletonHolder{

        //声明静态的实例
        private static final Singleton singleton = new Singleton();
    }

    //提供一个全局访问点,用于获取单例实例
    public static Singleton getInstance(){

        return SingletonHolder.singleton;
    }
}
